package web;

import com.tg.mapper.UserMapper;
import com.tg.pojo.User;
import com.tg.util.SqlSessionFactorys;
import lombok.SneakyThrows;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        /*InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);*/
        SqlSessionFactory sqlSessionFactory = SqlSessionFactorys.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.selecByUserName(username);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if (user != null) {
            writer.write("<script>alert('用户名已存在');" +
                    "document.write('3秒跳转到首页...');" +
                    "  setTimeout(function () {" +
                    "    location.href = 'http://localhost:8080/request-demo/register.html';" +
                    "  },3000);</script>");
            System.out.println(user.getUserName());
        } else {
            UserMapper mapper1 = sqlSession.getMapper(UserMapper.class);
            int insert = mapper1.insert(username, password);
            System.out.println(insert);
            writer.write("<script>alert('注册成功!');</script>");
        }
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
